package com.songcan.oauth.controller;



import com.songcan.common.exception.ObjectNotException;
import com.songcan.model.oauth.OauthClientDetails;
import com.songcan.oauth.service.OauthClientDetailsService;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.Objects;


@Validated
@AllArgsConstructor
@RestController
@RequestMapping("rest/client")
public class ClientDetailController {

    private final OauthClientDetailsService oauthClientDetailsService;


    @PostMapping()
    public void addOauthClient(@NotBlank(message = "clientId不能为空")String clientId,
                               @NotBlank(message = "clientSecret不能为空")String clientSecret,
                               String resourceIds, String scope,
                               @NotBlank(message = "令牌范围不能为空") String authorizedGrantTypes,
                               String webServerRedirectUri, String authorities,
                               @RequestParam(defaultValue = "50000")Integer accessTokenValidity,
                               @RequestParam(defaultValue = "50000")Integer refreshTokenValidity,
                               String autoapprove,String additionalInformation){
        OauthClientDetails oauthClientDetails = oauthClientDetailsService.getById(clientId);
        if(Objects.nonNull(oauthClientDetails)){
            throw new ObjectNotException("令牌已经存在");
        }
        oauthClientDetails = new OauthClientDetails(clientId,resourceIds,clientSecret,scope,authorizedGrantTypes,webServerRedirectUri,authorities,accessTokenValidity,refreshTokenValidity,additionalInformation,autoapprove);
        oauthClientDetailsService.save(oauthClientDetails);
    }


    @PutMapping()
    public void updateOauthClient(@NotBlank(message = "clientId不能为空")String clientId,
                                  @NotBlank(message = "clientSecret不能为空")String clientSecret,
                                  String resourceIds, String scope,
                                  @NotBlank(message = "令牌范围不能为空") String authorizedGrantTypes,
                                  String webServerRedirectUri, String authorities,
                                  @RequestParam(defaultValue = "50000")Integer accessTokenValidity,
                                  @RequestParam(defaultValue = "50000")Integer refreshTokenValidity,
                                  String autoapprove,String additionalInformation){
        OauthClientDetails oauthClientDetails = new OauthClientDetails(clientId,resourceIds,clientSecret,scope,authorizedGrantTypes,webServerRedirectUri,authorities,accessTokenValidity,refreshTokenValidity,additionalInformation,autoapprove);
        oauthClientDetailsService.saveOrUpdate(oauthClientDetails);
    }

}
